package leetcode.list;

import gaobo.singlelist.MySingleList;

//两数相加 力扣2
public class AddTwoNumbers {
      static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);//新链表的头节点
        ListNode preNode = res;
        int a = 0;//表示进位
        while (l1 != null || l2 != null || a != 0){
            int sum = a;
            if(l1 != null){
                sum += l1.val;
                l1 = l1.next;
            }
            if(l2 != null){
                sum += l2.val;
                l2 = l2.next;
            }
            //创建新的结点，存储计算结果
            preNode.next = new ListNode(sum %10);
            a = sum / 10;
            //更新当前结点
            preNode = preNode.next;
        }
        return res.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);

        ListNode listNode = addTwoNumbers(l1,l2);
        show(listNode);

    }
    private static void show(ListNode node){
        System.out.println("输出结果:");
        while (node != null){
            System.out.print(node.val+" ");
            node = node.next;
        }
    }


}

